package com.example.pilipili.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.pilipili.common.R;
import com.example.pilipili.pojo.dto.APDto;
import com.example.pilipili.pojo.entity.Admin;
import com.example.pilipili.pojo.entity.User;
import com.example.pilipili.service.AdminPrivilegesService;
import com.example.pilipili.service.AdminService;
import com.example.pilipili.utils.JwtU;
import com.example.pilipili.utils.MD5U;
import jakarta.servlet.http.HttpSession;
import jakarta.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/admins")
public class AdminController {
    @Autowired
    AdminService adminService ;

    @Autowired
    AdminPrivilegesService apService ;

    /**
     * 登录
     * @param admin phone,password
     * @param session
     * @return admin
     */
    @PostMapping("/login")
    public R<APDto> login(@RequestBody @Valid Admin admin, HttpSession session) {
        QueryWrapper<Admin> qw = new QueryWrapper<>() ;
        qw.eq("phone",admin.getPhone()).eq("password", MD5U.getMD5Password(admin.getPassword())) ;
        Admin admin1 = adminService.getOne(qw) ;
        if(admin1 == null) {
            return R.failed("账号或密码错误");
        }
        admin1.setPassword(null);
        Map<String, Object> info = new HashMap<>();
        info.put("name", admin1.getName());
        session.setAttribute("token", JwtU.sign(String.valueOf(admin.getId()),info ));
        return apService.getPListByUId(admin1.getId());
    }

    /**
     * 注册
     * @param admin uname,phone,password
     * @return null
     */
    @PostMapping("/register")
    public R register(@RequestBody @Valid Admin admin) {
        return adminService.add(admin);
    }


}
